<template>
  <div>
    <FixedOperation>
      <!-- 内容 -->
      <el-row :gutter="20">
        <!--产品分类-->
        <el-col :span="24" :xs="24">
          <div class="text-right">
            <el-button type="primary" @click="handleSubmit">保存</el-button>
            <el-button type="primary" plain @click="handleReturn"
              >返回</el-button
            >
            <!-- <el-button icon="Refresh" @click="handleReset(form)"
              >重置</el-button
            > -->
          </div>
        </el-col>
      </el-row>
    </FixedOperation>
    <div class="app-container combo-form">
      <el-form
        ref="form"
        :model="formData"
        label-width="140px"
        :rules="formRules"
      >
        <el-collapse v-model="activeNames">
          <el-collapse-item name="1" disabled>
            <template #title>
              <TitleName
                title="套餐基本信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row>
              <el-col :span="12">
                <el-form-item label="套餐名称" prop="name">
                  <el-input
                    v-model="formData.name"
                    placeholder="请输入套餐名称"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="formData.number">
                <el-form-item label="套餐编码" prop="number">
                  <el-input
                    disabled
                    v-model="formData.number"
                    placeholder="请输入套餐编码"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="价格含税" prop="isTax">
                  <el-radio-group v-model="formData.isTax">
                    <el-radio
                      v-for="item in yes_or_no"
                      :key="item.value"
                      :label="item.value"
                      >{{ item.label }}</el-radio
                    >
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="套餐价格" prop="price">
                  <el-input
                    disabled
                    v-model="formData.price"
                    placeholder="请输入销售价"
                    ><template v-slot:append>元</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="备注说明" prop="remark">
                  <el-input
                    v-model="formData.remark"
                    type="textarea"
                    rows="4"
                    maxlength="100"
                    show-word-limit
                    placeholder="请输入备注说明"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-item>
          <el-collapse-item name="1" disabled>
            <template #title>
              <TitleName
                title="套餐包含产品信息"
                icon="i-carbon-bookmark-filled"
                :titleStyle="{ color: '#000' }"
              ></TitleName>
            </template>
            <el-row>
              <el-col :span="24">
                <avue-crud
                  ref="crud"
                  :option="crudOption"
                  :data="formData.productInfoList"
                >
                  <template #menu-left> </template>
                  <template #productId-form="{ row }">
                    <el-select
                      v-model="row.productId"
                      placeholder="请选择产品"
                      class="w-full"
                      suffix-icon="Search"
                      remote-show-suffix
                      :suffix-transition="false"
                      filterable
                      :props="{
                        value: 'id',
                        label: 'name'
                      }"
                      remote
                      :remote-method="queryProduct"
                      @change="rowChange(row)"
                    >
                      <el-option
                        v-for="item in productOptions"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                        <div>
                          <span>{{ item.name }}</span>
                          <span>({{ item.number }})</span>
                        </div>
                      </el-option>
                    </el-select>
                  </template>
                  <template #menu="{ row, index }">
                    <el-button
                      plain
                      icon="Delete"
                      link
                      @click="delRow(row, index)"
                      >删除</el-button
                    >
                  </template>
                  <template #empty>
                    <div>暂无数据</div>
                  </template>
                  <template #footer>
                    <el-button
                      plain
                      type="primary"
                      icon="Plus"
                      class="w-full"
                      @click="addProduct"
                      >添加产品</el-button
                    >
                  </template>
                </avue-crud>
              </el-col></el-row
            >
          </el-collapse-item>
        </el-collapse>
      </el-form>
    </div>
  </div>
</template>
<script setup name="ComboForm">
import { reactive, toRefs, ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import usePassData from '@/store/modules/passData'
import FixedOperation from '@/components/FixedOperation'
import useCommonStore from '@/store/modules/common'
import {
  listOrdproduct,
  setOrdcombo,
  getOrdcombo,
  getOrdproduct
} from '@/api/productMange/product'
import useTagsViewStore from '@/store/modules/tagsView'
const router = useRouter()
const route = useRoute()
const commonStore = useCommonStore()
const passData = usePassData()
const { proxy, type } = getCurrentInstance()
const sortOptions = ref([])
const companyData = ref([])
commonStore.getCompanyData().then(e => {
  companyData.value = e
})

const {
  ord_product_plate_type,
  ord_product_plate,
  yes_or_no,
  measurement_unit,
  credit_rating,
  quantity_accuracy,
  device_type,
  warehouse_info,
  self_product,
  transaction_type
} = proxy.useDict(
  'ord_product_plate_type',
  'ord_product_plate',
  'yes_or_no',
  'measurement_unit',
  'credit_rating',
  'quantity_accuracy',
  'device_type',
  'warehouse_info',
  'self_product',
  'transaction_type'
)

const props = defineProps({
  comboData: {
    type: Object,
    require: true,
    default: null
  }
})
const data = reactive({
  activeNames: ['1'],
  formData: {
    productInfoList: [],
    price: 0
  },
  crudOption: {
    header: false,
    menu: true,
    delBtn: false,
    editBtn: false,
    addBtn: false,
    addRowBtn: false,
    saveBtn: false,
    cancelBtn: false,
    cellBtn: false,
    // searchBtn: false,
    refreshBtn: false,
    columnBtn: false,
    menuWidth: 250,
    column: [
      {
        label: '选择产品',
        prop: 'productId',
        rules: [
          {
            required: true,
            message: '请选择产品',
            trigger: 'blur'
          }
        ],
        cell: true
      },
      {
        label: '产品名称',
        prop: 'name',
        cell: false,
        rules: [
          {
            required: true,
            message: '请输入产品名称',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '产品编号',
        prop: 'number'
      },
      {
        label: '规格型号',
        prop: 'specification',
        rules: [
          {
            required: true,
            message: '请输入年龄',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '单位',
        prop: 'unit',
        type: 'select',
        dicData: measurement_unit,
        rules: [
          {
            required: true,
            message: '请输入单位',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '单价',
        prop: 'price',
        rules: [
          {
            required: true,
            message: '请输入单价',
            trigger: 'blur'
          }
        ]
      },
      {
        label: '数量',
        prop: 'num',
        type: 'number',
        min: 0,
        class: 'w-full',
        precision: 0,
        rules: [
          {
            required: true,
            message: '请输入数量',
            trigger: 'blur'
          }
        ],
        cell: true
      }
    ]
  },

  formRules: {
    name: [
      {
        required: true,
        message: '请输入编号',
        trigger: 'blur'
      }
    ],
    price: [
      {
        required: true,
        message: '请输入销售价',
        trigger: 'change'
      }
    ]
  },
  productOptions: []
})
const { formData, crudOption, formRules, activeNames, productOptions } =
  toRefs(data)
watch(
  () => data.formData.productInfoList,
  (newVal, oldValue) => {
    let price = 0
    formData.value.productInfoList.forEach(e => {
      if (e.id) {
        price = e.price * e.num + price
      }
    })
    formData.value.price = price
  },
  { deep: true }
)
watchEffect(() => {
  if (route.query.comboId && route.name == type.name) {
    getFormData(route.query.comboId)
  }
})
/** 获取产品详情
 * @param {number}  id 表单id
 */
function getFormData(id) {
  getOrdcombo(id).then(res => {
    let resData = {}
    resData = res.data
    productOptions.value = resData.productInfoList.map((e, i) => {
      let item
      item = { ...e, id: e.productId }
      return item
    })
    resData.productInfoList.forEach((e, i) => {
      if (e.id) {
        resData.productInfoList[i].$cellEdit = true
      }
    })
    formData.value = resData
  })
}

// 初始化
function init() {}
function handleSubmit(e) {
  console.log('保存-<>', formData.value)
  proxy.$refs.form.validate((valid, done, msg) => {
    proxy.$refs.crud.validateCellForm().then(err => {
      if (valid && !err) {
        setOrdcombo(formData.value).then(res => {
          // proxy.$modal.msgSuccess(res.data.id ? '修改成功' : '新增成功')
          // if (!formData.value.id) {
          //   useTagsViewStore().delView(router.currentRoute.value)
          //   router.go(-1)
          // }
          // 保存接口才有
          proxy.useReturn(
            '',
            () => {
              //返回上一步
              handleReturn()
            },
            async () => {
              //继续
            }
          )
          let productInfoList = res.data.productInfoList.map(e => {
            return {
              ...e,
              $cellEdit: true
            }
          })
          formData.value = { ...res.data, productInfoList }
          console.log('formData.value==>', formData.value)
        })
      }
    })
  })
}

function handleReset() {
  console.log('清除')
  formData.value = {
    productInfoList: [],
    price: 0
  }
  proxy.resetForm('sortRef')
  //   proxy.$refs.form.resetForm()
}
// 产品模糊检索
function queryProduct(val) {
  if (!val) return
  let params = {
    pageNum: 1,
    pageSize: 10,
    status: 1,
    keyword: val
  }
  listOrdproduct(params).then(res => {
    productOptions.value = res.rows
  })
}
// 产品赋值
function rowChange(row) {
  console.log('row==>', row.productId)
  if (!row.productId) return
  getOrdproduct(row.productId).then(res => {
    formData.value.productInfoList.forEach((e, i) => {
      if (e.productId == res.data.id) {
        formData.value.productInfoList[i] = {
          ...{ $cellEdit: true, productId: row.productId, num: 1 },
          ...res.data
        }
      }
    })
    console.log('row1==>', formData.value.productInfoList)
  })
}
// 添加产品
function addProduct() {
  formData.value.productInfoList.push({ $cellEdit: true })
  console.log('product==>', formData.value.productInfoList)
}
// 删除行
function delRow(row, index, done) {
  proxy
    .$confirm('是否删除该产品', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      formData.value.productInfoList.splice(index, 1)
      proxy.$message({
        type: 'success',
        message: '删除成功!'
      })
    })
    .catch(() => {})
}

function handleReturn() {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
  // router.push({ path: url, query: data })
  //   proxy.$refs.form.clearValidate()
}
init()
</script>
<style scoped>
.form-title {
  color: #111111;
}
.combo-form:deep(.form-title:before) {
  content: '▋';
  display: inline-block;
  color: #409eff;
}
:deep(.avue-crud__empty) {
  padding: 0;
}
</style>
